package com.app.qbake;

import android.content.Context;
import android.graphics.Color;
import android.os.Environment;
import android.support.multidex.MultiDexApplication;
import android.support.v4.app.Fragment;
import android.text.TextUtils;

import com.app.qbake.base.di.AppComponent;
import com.app.qbake.base.di.DaggerAppComponent;
import com.app.qbake.module.square.activity.SellerHomeActivity;
import com.app.qbake.util.AliPaiUtil;
import com.app.qbake.util.GlideImageLoader;
import com.mabeijianxi.smallvideorecord2.DeviceUtils;
import com.mabeijianxi.smallvideorecord2.JianXiCamera;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.api.UIKitOptions;
import com.netease.nim.uikit.api.model.session.SessionEventListener;
import com.netease.nim.uikit.business.contact.core.query.PinYin;
import com.netease.nim.uikit.config.DemoCache;
import com.netease.nim.uikit.config.preference.Preferences;
import com.netease.nim.uikit.config.preference.UserPreferences;
import com.netease.nim.uikit.impl.NimUIKitImpl;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.util.NIMUtil;
import com.pingplusplus.android.Pingpp;
import com.umeng.analytics.AnalyticsConfig;
import com.wind.base.C;
import com.wind.base.Globe;
import com.wind.base.http.HeaderParams;
import com.wind.base.utils.AppUtil;
import com.wind.umengsharelib.UmengUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.https.HttpsUtils;

import java.io.File;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import cn.finalteam.galleryfinal.CoreConfig;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.ImageLoader;
import cn.finalteam.galleryfinal.ThemeConfig;
import dagger.android.AndroidInjector;
import dagger.android.DispatchingAndroidInjector;
import dagger.android.support.HasSupportFragmentInjector;
import okhttp3.OkHttpClient;

public class App extends MultiDexApplication implements HasSupportFragmentInjector {

    private static App sInstance;
    private AppComponent mAppComponent;

    @Override
    public void onCreate() {
        super.onCreate();
        sInstance = this;
       // CaocConfig.Builder.create().apply();
        mAppComponent = createComponent();
        mAppComponent.inject(this);
        initUmeng();
        initHeaderParams();
        initGallery();
        initOkHttp();

        Globe.sAppContext = sInstance;

        AliPaiUtil.init();

        DemoCache.setContext(this);
        // 4.6.0 开始，第三方推送配置入口改为 SDKOption#mixPushConfig，旧版配置方式依旧支持。
        NIMClient.init(this, getLoginInfo(), NimSDKOptionConfig.getSDKOptions(this));
        // 以下逻辑只在主进程初始化时执行
        // 以下逻辑只在主进程初始化时执行
        if (NIMUtil.isMainProcess(this)) {

            // 注册自定义推送消息处理，这个是可选项
           // NIMPushClient.registerMixPushMessageHandler(new DemoMixPushMessageHandler());

            // 初始化红包模块，在初始化UIKit模块之前执行
           // NIMRedPacketClient.init(this);
            // init pinyin
            PinYin.init(this);
            PinYin.validate();
            // 初始化UIKit模块
            initUIKit();
            // 初始化消息提醒
            NIMClient.toggleNotification(UserPreferences.getNotificationToggle());
            // 云信sdk相关业务初始化
            NIMInitManager.getInstance().init(true);
            // 初始化音视频模块
          //  initAVChatKit();
            // 初始化rts模块
            //initRTSKit();
            NimUIKitImpl.setSessionListener(new SessionEventListener() {
                @Override
                public void onAvatarClicked(Context context, IMMessage message) {
                    String fromAccount=message.getFromAccount();
                    SellerHomeActivity.start(context,fromAccount);
                }

                @Override
                public void onAvatarLongClicked(Context context, IMMessage message) {

                }

                @Override
                public void onAckMsgClicked(Context context, IMMessage message) {

                }
            });
        }
    }

    private void initUmeng() {
        UmengUtil.initUmeng(this);



    }
    private LoginInfo getLoginInfo() {
        String account = Preferences.getUserAccount();
        String token = Preferences.getUserToken();

        if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(token)) {
            DemoCache.setAccount(account.toLowerCase());
            return new LoginInfo(account, token);
        } else {
            return null;
        }
    }
    private void initUIKit() {
        // 初始化
         NimUIKit.init(this, buildUIKitOptions());

        // 设置地理位置提供者。如果需要发送地理位置消息，该参数必须提供。如果不需要，可以忽略。
       // NimUIKit.setLocationProvider(new NimDemoLocationProvider());

        // IM 会话窗口的定制初始化。
       // SessionHelper.init();

        // 聊天室聊天窗口的定制初始化。
        //ChatRoomSessionHelper.init();

        // 通讯录列表定制初始化
        //ContactHelper.init();

    }

    private UIKitOptions buildUIKitOptions() {
        UIKitOptions options = new UIKitOptions();

        // 设置app图片/音频/日志等缓存目录
        options.appCacheDir = NimSDKOptionConfig.getAppCacheDir(this) + "/app";
        return options;
    }

    private void initMiniVideo() {
        // 设置拍摄视频缓存路径
        File dcim = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        if (DeviceUtils.isZte()) {
            if (dcim.exists()) {
                JianXiCamera.setVideoCachePath(dcim + "/mabeijianxi/");
            } else {
                JianXiCamera.setVideoCachePath(dcim.getPath().replace("/sdcard/",
                        "/sdcard-ext/")
                        + "/mabeijianxi/");
            }
        } else {
            JianXiCamera.setVideoCachePath(dcim + "/mabeijianxi/");
        }
        // 初始化拍摄，遇到问题可选择开启此标记，以方便生成日志
        JianXiCamera.initialize(false,null);
    }


    private void initOkHttp() {
        HttpsUtils.SSLParams sslParams= HttpsUtils.getSslSocketFactory(null, null, null);
        // HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
//                .addInterceptor(new LoggerInterceptor("TAG"))
                //.addInterceptor(new DecryptInterceptor())
                .sslSocketFactory(sslParams.sSLSocketFactory)
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                //其他配置
                .build();


        OkHttpUtils.initClient(okHttpClient);
    }

    private void initHeaderParams() {
        Globe.sDebug = false;
        Pingpp.DEBUG = false;
        String channel=AnalyticsConfig.getChannel(this);

        HeaderParams params = new HeaderParams.Builder()
                .pkg(AppUtil.getAppPackageName(this))
                .appVersion(C.Version.APP_VERSION)
                .channel(channel)
                .osVersion(AppUtil.getOsVersion())
                .deviceName(AppUtil.getDeviceBrand())
                .build();
        Globe.sHeaderParams = params;



    }

    private void initGallery() {
        //设置主题
//ThemeConfig.CYAN
        ThemeConfig theme = new ThemeConfig.Builder()
                .setTitleBarIconColor(Color.parseColor("#333333"))
                .setTitleBarTextColor(Color.parseColor("#333333"))
                .setTitleBarBgColor(Color.parseColor("#ffffff"))
                .setFabNornalColor(Color.parseColor("#ED705D"))
                .setFabPressedColor(Color.parseColor("#ED705D"))
                .setCheckSelectedColor(Color.parseColor("#ED705D"))
                .build();
//配置功能
        FunctionConfig functionConfig = new FunctionConfig.Builder()
                .setEnableCamera(true)
                .setEnableEdit(true)
                .setEnableCrop(true)
                .setEnableRotate(true)
                .setCropSquare(true)
                .setEnablePreview(true)
                .setForceCrop(true)
                .setForceCropEdit(false)
                .build();

//配置imageloader
        ImageLoader imageloader = new GlideImageLoader();
        CoreConfig coreConfig = new CoreConfig.Builder(this, imageloader, theme)
                //.setDebug(BuildConfig.DEBUG)
                .setFunctionConfig(functionConfig)
                .build();
        GalleryFinal.init(coreConfig);
    }

    /**
     * 获取渠道名称
     */
    public static String getChannelName() {
        return AnalyticsConfig.getChannel(sInstance);
    }

    public static App get() {
        return sInstance;
    }

    private AppComponent createComponent() {
        return DaggerAppComponent
                .builder()
                .build();

    }

    public AppComponent appComponent() {
        return mAppComponent;
    }

    @Inject
    DispatchingAndroidInjector<android.support.v4.app.Fragment> dispatchingAndroidInjector;


    @Override
    public AndroidInjector<Fragment> supportFragmentInjector() {
        return dispatchingAndroidInjector;
    }
}
